package com.zzt.video.task;

import com.zzt.video.model.dto.AdvertiseDto;
import com.zzt.video.model.dto.AdvertiseShowDto;
import com.zzt.video.model.entity.Advertise;
import com.zzt.video.service.AdvertiseService;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class AdvertiseRedisTask {

    @Autowired
    private AdvertiseService advertiseService;

    @Autowired
    private RedissonClient redissonClient;

    // 定时任务，每30分钟执行一次
    @Scheduled(fixedRate = 30 * 60 * 1000)
    public void updateAdvertiseCache() {
        List<Advertise> advertises = advertiseService.getAdvertiseList();
        List<AdvertiseShowDto> showDtos = advertises.stream()
                .map(e -> {
                    AdvertiseShowDto item = new AdvertiseShowDto();
                    item.setId(e.getId());
                    item.setCoverUrl(e.getCoverUrl());
                    return item;
                })
                .collect(Collectors.toList());

        // 存储广告列表
        RBucket<List<AdvertiseShowDto>> advertiseBucket = redissonClient.getBucket("advertise:list");
        advertiseBucket.set(showDtos);

        // 存储单个广告详情
        for (Advertise advertise : advertises) {
            AdvertiseDto dto = new AdvertiseDto(advertise);
            RBucket<AdvertiseDto> advertiseDataBucket = redissonClient.getBucket("advertise:detail:" + advertise.getId());
            advertiseDataBucket.set(dto);
        }
    }
}

